import { useSyncExternalStore } from "react"

export default function useHistory() {
  const url = useSyncExternalStore(
    (callback) => {
      window.addEventListener('popstate', callback)
      window.addEventListener('hashchange', callback)
      return () => {
        window.removeEventListener('popstate', callback)
        window.removeEventListener('hashchange', callback)
      }
    },
    () => location.href
  )
  function push(t: string) {
    window.history.pushState({}, '', t)
    window.dispatchEvent(new PopStateEvent('popstate'))
  }
  function replace(t: string) {
    window.history.replaceState({}, '', t)
    window.dispatchEvent(new PopStateEvent('popstate'))
  }
  return [url, push, replace] as const
}